package org.example.ratelimit2;

import org.example.ratelimit2.impl.LeakyBucketRateLimiter;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class LeakyBucketRateLimiterTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Queue<Integer> queue = new ArrayDeque<>();
        // 桶大小为10，每秒放行2个
        LeakyBucketRateLimiter limiter = new LeakyBucketRateLimiter(10,2);

        executorService.submit(() -> {
            int count = 0;
            while (true) {
                if (limiter.tryAcquire()) {
                    queue.offer(count);
                    System.out.println(count + "--------流量被放行--------");
                } else {
                    System.out.println(count + "流量被限制");
                }
                count++;
                try {
                    Thread.sleep((long) (Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(()->{
            if (!queue.isEmpty()) {
                System.out.println(queue.poll() + "请求被处理");
            }
        }, 0, 2, TimeUnit.SECONDS);

        try {
            Thread.sleep(Integer.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
